package com.huifaapp.mall.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.JsonBean;
import com.huifaapp.mall.bean.JsonFileReader;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class DeliveryActivity extends Activity {

    private EditText edName,edPhone,edAddress,edJd;
    private TextView tvCity;
    private TextView tvCittset;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<String> arr=new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Button btSaveset;
    private Switch stMr;
    private String mr = 0+"";
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery);
        initView();
        initData();
        initJsonData();
    }




    private void initView() {
        edName = (EditText) findViewById(R.id.delivery_name);
        edPhone = (EditText) findViewById(R.id.delivery_phone);
        edAddress = (EditText) findViewById(R.id.delivery_address);
        tvCity = (TextView) findViewById(R.id.delivery_city);
        tvCittset = (TextView) findViewById(R.id.delivery_cityset);
        btSaveset = (Button) findViewById(R.id.delivery_saveset);
        stMr = (Switch) findViewById(R.id.delivery_mr);











    }

    private void initData() {

        Intent intent = getIntent();
        final String name1 = intent.getStringExtra("name");
        final String phone1 = intent.getStringExtra("phone");
        final String city1 = intent.getStringExtra("city");
        final String xiangxi1 = intent.getStringExtra("xiangxi");


        edName.setText(name1);
        edPhone.setText(phone1);
        tvCittset.setText(city1);
        edAddress.setText(xiangxi1);

        tvCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerView();
            }

        });
        stMr.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    mr = 1+"";
                }else {
                    mr = 0+"";
                }
            }
        });
        btSaveset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentfh = getIntent();
                String id =  intentfh.getStringExtra("idid");
                Log.e("更改id",id);
                if (id.equals("1")){
                    final String name2 = edName.getText().toString();
                    final String phone2 = edPhone.getText().toString();
                    final String adress2 = edAddress.getText().toString();
                    final String city2 = tvCittset.getText().toString();
if(phone2.length()==11) {


    Intent intent = getIntent();
    String addrid = intent.getStringExtra("addrId");
    OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL + "users/address/edit")
            .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
            .addParams("appId", AUniqueIdentifier.getDeviceId(DeliveryActivity.this))
            .addParams("addrId", addrid)
            .addParams("receiverName", name2)
            .addParams("city", city2)
            .addParams("detail", adress2)
            .addParams("receiverPhone", phone2)
            .addParams("isdefault", mr)
            .build()
            .execute(new StringCallback() {
                @Override
                public void onError(Request request, Exception e) {

                }

                @Override
                public void onResponse(String response) {
                    Log.e("response", response);
                    ToastUtils.showShort("修改成功");
                    finish();
                }
            });
            }else{
                Toast.makeText(DeliveryActivity.this,"手机号不能少于11位",Toast.LENGTH_SHORT).show();
            }
                }else {

                    final String name = edName.getText().toString();
                    final String phone = edPhone.getText().toString();
                    final String adress = edAddress.getText().toString();
                    final String city = tvCittset.getText().toString();
                    if(phone.length()==11){
                    if (name.isEmpty()||phone.isEmpty()||adress.isEmpty()||city.isEmpty()){
                        ToastUtils.showShort("缺少必填参数");
                    }else {
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                OkHttpUtils.post()
                                        .url(ApiManager.BASE_NIUPAI_URL+"users/address/add")
//                                    .addParams("token","201712291124171334f3ed61d93e05404b8dc78f10c4770cf8")
//                                    .addParams("appId","D7B72681-8205-4C8F-8CCB-142C448203E3")
                                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                        .addParams("appId", AUniqueIdentifier.getDeviceId(DeliveryActivity.this))
                                        .addParams("receiverName",name)
                                        .addParams("city",city)
                                        .addParams("isdefault",mr)
                                        .addParams("detail",adress)
                                        .addParams("receiverPhone",phone)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {

                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                Log.e("HB",response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code = jsonObject.getString("code");
                                                    if (code.equals("10000")){ //请求成功！
                                                        ToastUtils.showShort("请求成功");
                                                        setResult(2020,new Intent());

                                                        finish();
                                                    }else {
                                                        ToastUtils.showShort("保存失败，请稍后再试...");
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });

                            }
                        });
                    }



                    }else{
                        Toast.makeText(DeliveryActivity.this,"手机号不能少于11位",Toast.LENGTH_SHORT).show();
                    }





                }
            }
        });
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                tvCittset.setText(text);
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(15)
                .setOutSideCancelable(false)
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(arr, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份

            arr.add(jsonBean.get(i).getName());
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }
    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new  JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
